const fs = require("fs");
const qs = require("querystring");
const url = require("url");
const http = require("http");
const { title } = require("process");

http.createServer((req, res) => {
        if (req.url.includes("api")) {
            dataRes(req, res);
        } else {
            fileRes(req, res);
        }
    })
    .listen(3000, () => {
        console.log("服务器开启成功：http://localhost:3000");
    });

// 1.区分静态页面
function fileRes(req, res) {
    let p = url.parse(req.url).pathname;
    p = p === "/" ? `./static/index.html` : `./static${p}`;
    fs.readFile(p, (error, data) => {
        if (error) {
            res.write("not found");
        } else {
            res.write(data);
        }
        res.end();
    });
}

// 2.区分方法
function dataRes(req, res) {
    // 判断请求类型
    if (req.method === "GET") {
        distinguishPage(req, res, url.parse(req.url, true).query);
    } else if (req.method === "POST") {
        let str = "";
        req.on("data", (chunk) => {
            str += chunk;
        });
        req.on("end", () => {
            distinguishPage(req, res, qs.parse(str));
        });
    }
}

// 3.区分页面
function distinguishPage(req, res, data) {
    switch (data.type) {
        case "index":
            index(req, res, data);
            break;
        case "goodsList": //商品列表
            goodsList(req, res, data);
            break;
        case "getGoods": //详情页添加
            getGoods(res);
            break;
        case "cart": //购物车
            cart(req, res, data);
        case "login":
            login(req, res, data);
            break;
        case "register":
            register(req, res, data);
            break;
        default:
            error(req, res, data);
    }
}

// 4.页面处理请求数据和返回数据
function index(req, res, data) {
    console.log("index");
    let dataObj = {
        code: "200",
        title: "",
        data: [],
    };
    fs.readFile("./data/banner.json", "utf-8", (error, data) => {
        if (error) {
            (dataObj.code = "400"), (dataObj.title = "获取轮播图数据出错");
        } else {
            (dataObj.title = "获取轮播图数据出错"), (dataObj.data = JSON.parse(data));
        }
    });
}

//详情页添加的功能
//http://localhost:3000/api?type=getGoods
function getGoods(res) {
    fs.readFile("./data/database.json", "utf-8", (err, data) => {
        const obj = {};
        if (err) {
            (obj.code = 444), (obj.title = "获取商品失败"), (obj.data = []);
        } else {
            (obj.code = 666),
            (obj.title = "获取商品成功"),
            (obj.data = JSON.parse(data));
        }
        res.write(JSON.stringify(obj));
        res.end();
    });
}

function goodsList(req, res, data) {
    fs.readFile("./data/goodsList.json", "utf-8", (error, data) => {
        const dataObj = {
            code: "200",
            title: "",
            data: [],
            // 分页数据
            // ,pageNo: 0,
            // totalCount: 5,
            // totalPage: 0
        };
        // 电脑，洁面，运动鞋，手机，面膜，零食
        // 筛选 - 销量，新品，价格，收货地址，考拉自营，有货，考拉出品
        if (error) {
            dataObj.code = "400";
            dataObj.title = "获取商品列表数据失败";
        } else {
            dataObj.title = "获取商品列表数据成功";
            dataObj.data = [...JSON.parse(data)];
        }
        // console.log( data, dataObj);
        res.write(JSON.stringify(dataObj));
        res.end();
    });
}

//购物车
function cart(req, res, data) {
    fs.readFile("./data/cart.json", "utf-8", (error, data) => {
        // console.log(JSON.parse(data));

        const dataObj = {
            code: "200",
            title: "",
            data: [],
            // 分页数据
            // ,pageNo: 0,
            // totalCount: 5,
            // totalPage: 0
        };
        if (error) {
            dataObj.code = "400";
            dataObj.title = "获取购物车数据失败";
        } else {
            dataObj.title = "获取购物车数据成功";
            dataObj.data = JSON.parse(data);
        }
        // console.log( data, dataObj);
        res.write(JSON.stringify(dataObj));
        res.end();
    });
}

// 登录注册功能
function register(req, res, q) {
    fs.readFile("./data/userMsg.json", "utf-8", (err, data) => {
        // console.log(data)
        if (err) {
            res.write(
                JSON.stringify({
                    code: 404,
                    title: "获取用户信息失败",
                    data: null,
                })
            );
            res.end();
        } else {
            const arr = JSON.parse(data);
            const flag = arr.some((val) => val.username === q.username);
            if (flag) {
                res.write(
                    JSON.stringify({
                        code: 303,
                        title: "用户名重复",
                        data: null,
                    })
                );
                res.end();
            } else {
                arr.push({
                    username: q.username,
                    password: q.password,
                });
                // 存回去
                fs.writeFile("./data/userMsg.json", JSON.stringify(arr), (err) => {
                    if (err) {
                        res.write(
                            JSON.stringify({
                                code: 202,
                                title: "写入新用户失败",
                                data: null,
                            })
                        );
                        res.end();
                    } else {
                        res.write(
                            JSON.stringify({
                                code: 101,
                                title: "注册成功",
                                data: {
                                    username: q.username,
                                    password: q.password,
                                },
                            })
                        );
                        res.end();
                    }
                });
            }
        }
    });
}

function login(req, res, w) {
    fs.readFile("./data/userMsg.json", "utf-8", (err, data) => {
        // 获取失败
        if (err) {
            res.write(
                JSON.stringify({
                    code: 0,
                    title: "获取初始用户信息失败",
                    data: null,
                })
            );
            res.end();
        } else {
            // 获取成功
            const arr = JSON.parse(data);
            let i = 0;
            const flag = arr.some((val, idx) => {
                i = idx;
                // console.log(val.username)
                // console.log(w.username)
                return val.username === w.username;
            });
            if (flag) {
                // 用户名存在，该判断密码了
                // 如果密码一致  登录成功
                if (arr[i].password === w.password) {
                    res.write(
                        JSON.stringify({
                            code: 1,
                            title: "登录成功",
                            data: arr[i],
                        })
                    );
                    res.end();
                } else {
                    // 用户名，密码不一致
                    res.write(
                        JSON.stringify({
                            code: 2,
                            title: "密码错误",
                            data: null,
                        })
                    );
                    res.end();
                }
            } else {
                // 查询不到用户名
                res.write(
                    JSON.stringify({
                        code: 3,
                        title: "无此用户名",
                        data: null,
                    })
                );
                res.end();
            }
        }
    });
}

// 错误页面
function error(req, res, data) {
    res.write({
        code: 400,
        title: data.type,
        data: null,
    });
    res.end();
}